<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>章可次</title>
</head>
<body>
    <canvas id="canvas" width="600" height="600"></canvas>
<input type="file" id="file" multiple="multiple">
<script>
    var eleFile=document.querySelector('#file');
    var file = null;

    // html5
    var reader = new FileReader();
    var img = new Image();
    var canvas=document.createElement('canvas');
    var context=canvas.getContext('2d');

    reader.onload=function(e){
        // console.log(e.target.result);   // base 64 图片
        img.src=e.target.result;
        document.body.appendChild(img);
    }
    img.onload=function(){
        var originWidth=this.width;
        var originHeight = this.height;

        // 如何做文件的压缩
        // console.log(originWidth,originHeight);
        var maxWidth = 400,maxHeight=400;  // 限制大小
        var targetWidth = originWidth,targetHeight=originHeight;
        if(originHeight>maxHeight || originWidth>maxWidth){
            if(originWidth / originHeight > maxWidth / maxHeight){
                targetWidth=maxWidth;
                targetHeight=Math.round(maxWidth*(originHeight/originWidth));
            }
            else{
                targetHeight=maxHeight;
                targetWidth=maxHeight*(originWidth/originHeight);
            }
            // console.log(targetWidth,targetHeight);
        }
        canvas.width=targetWidth;
        canvas.height-=targetHeight;
        context.drawImage(img,0,0,targetWidth,targetHeight);
        document.body.appendChild(canvas);
    }
    eleFile.addEventListener('change',function(event){
        // console.log(event);
        file = event.target.files[0];
        // console.log(file.type);
        // 图片
        if(file.type.indexOf('image')===0){
            reader.readAsDataURL(file);
            // console.log(file);
        }
    })
</script>
<!-- <script>
    const canvas=document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    // 圆心
    ctx.translate(300,300);
    ctx.beginPath()
    ctx.arc(0,0,100,0,2*Math.PI)
    ctx.stroke();
    ctx.closePath();

    ctx.beginPath();
    ctx.arc(0,0,5,0,2*Math.PI)
    ctx.stroke();
    ctx.closePath();
</script> -->
</body>
</html>